<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\Api\UserTags;
use App\Model\Api\UserTagsCat;

use App\Model\Number;
use App\Model\OperationLogs;

use App\Model\Permissions;
use App\Model\Roles;
use App\Model\UserAccountCancelLog;
use App\Model\Users;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    public function __construct(Request $request, Users $users)
    {
        parent::__construct($request);
        $this->model = $users;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $input = $request->input();
        return $this->toJson(self::SUCCESS,$this->model->getAllList($input));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|unique:mysql.users,name|max:50',
            'password' => 'required|confirmed',
            'checkedCities' => 'required'
        ],[
            'name.required' => '用户名不可为空',
            'name.unique' => '用户名已存在',
            'name.max' => '用户名不可超过50个字符',
            'password.required' => '密码不可为空',
            'password.confirmed' => '两次输入密码不一致',
            'checkedCities.required' => '角色不可为空',
        ]);
        if($validator->fails()){
            return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
        }

        $rolesIdArr = $request->input('checkedCities');
        $rolesArr = [];
        $roles = Roles::get()->whereIn('id', $rolesIdArr);
        foreach ($roles as $v) {
            $rolesArr[] = $v->name;
        }

        $user = Users::create(collect($request->only(['name','password']))->merge(Users::generateApiToken())->toArray());
//        $roles = Roles::find($request->input('role_id'));
        $user->assignRole($rolesArr);
        OperationLogs::createData($request,OperationLogs::USER, '新增');
        return $this->toJson(self::SUCCESS, $user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|max:50',
            'checkedCities' => 'required'
        ],[
            'name.required' => '用户名不可为空',
            'name.max' => '权限名不可超过50个字符',
            'checkedCities.required' => '角色不可为空',
        ]);
        if($validator->fails()){
            return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
        }
        $user = Users::find($id);
        $user->name = $request->post('name');
        if($password = $request->post('password','')){
            $user->password = $password;
            $tokenRes = Users::generateApiToken();// 修改密码重置token
            $user->api_token = $tokenRes['api_token'];
            // 设置请求头token 记录日志使用token获取登录用户
            $request->headers->set('x-token', $tokenRes['api_token']);
        }
        $user->save();


        $rolesIdArr = $request->input('checkedCities');
        $rolesArr = [];
        $roles = Roles::get()->whereIn('id', $rolesIdArr);
        foreach ($roles as $v) {
            $rolesArr[] = $v->name;
        }
//        $roles = Roles::find($request->input('role_id'));
        $user->syncRoles($rolesArr);
        OperationLogs::createData($request,OperationLogs::USER, '编辑', $id);
        return $this->toJson(self::SUCCESS, $user);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,$id)
    {
        Users::destroy($id);
        OperationLogs::createData($request,OperationLogs::USER, '删除', $id);
        return $this->toJson();
    }

    public function logout(){
        return $this->toJson();
    }

    public function logs(Request $request, AdminLog $adminLog){
        return $this->toJson(self::SUCCESS, $adminLog->getList($request));
    }

    public function users(){
        return $this->toJson(self::SUCCESS, $this->model->getAdmins());
    }

    //用户注销
    public function userCancel(Request $request){

        $userId = $request->get('user_id');
        if (!$userId) {
            $this->toJson(self::ERROR, [], '参数错误');
        }

        $result = (new Number())->userCancel($userId);
        if(isset($result['code']) && $result['code'] == 0){
            return $this->toJson(self::SUCCESS,[]);
        }else{
            return $this->toJson(self::ERROR, [], $result['msg'] ?? "失败");

        }
    }

    public function userCancelLog(Request $request,UserAccountCancelLog $userCancelModel){
        return $this->toJson(self::SUCCESS, $userCancelModel->getList($request));
    }

    public function getUserTags(Request $request, UserTags $userTags) {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $type = $request->get('type', '');
        $catId = $request->get('catId', 0);

        return $this->toJson(self::SUCCESS, $userTags->getList($limit, $page,$type, $catId));
    }

    public function createUserTags(Request $request, UserTags $userTags) {
        $res = $userTags->createUserTag($request->except('_url'));
        return $res['code'] == 0 ? $this->toJson(self::SUCCESS) : $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function updateUserTags(Request $request, $id, UserTags $userTags) {
        $res = $userTags->updateUserTag(intval($id), $request->except('_url'));
        return $res['code'] == 0 ? $this->toJson(self::SUCCESS) : $this->toJson(self::ERROR, [], $res['msg']);
    }


/**
 * [checkCatStatus 标签分类有效隐藏状态]
 * @return
 *
 */
protected function checkCatStatus($catId)
{
    $catModel = new UserTagsCat();
    $info = $catModel->findById($catId);
    if (empty($info)) {
        return false;
    }
    return true;
}


/**
 * [getShowCatList 标签分类列表（显示）]
 */
public function getShowCatList(Request $request)
{
    $ifAll = $request->input('if_all', 1);
    $catModel = new UserTagsCat();
    if ($ifAll) {
        $catList = $catModel->getList();
    }else{
        $catList = $catModel->getShowList();
    }
    return $this->toJson(self::SUCCESS, $catList);
}

/**
 * [addTagsCat 添加分类]

 */
public function addTagsCat(Request $request)
{
    $validator = Validator::make($request->all(),[
        'name' => 'required|max:50',
    ],[
        'name.required' => '标签名不可为空',
        'name.max' => '权限名不可超过50个字符',
    ]);
    if($validator->fails()){
        return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
    }

    $modelUserTagsCat = new UserTagsCat();
    $res = $modelUserTagsCat->createUserTagsCat($request->except('_url'));
    return $res['code'] == 0 ? $this->toJson(self::SUCCESS) : $this->toJson(self::ERROR, [], $res['msg']);
}
/**
 * [addTagCat 添加分类]

 */
public function editTagsCat(Request $request, $id)
{
    $validator = Validator::make($request->all(),[
        'name' => 'required|max:50',
    ],[
        'name.required' => '用户名不可为空',
        'name.max' => '权限名不可超过50个字符',
    ]);
    if($validator->fails()){
        return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
    }

    $modelUserTagsCat = new UserTagsCat();
    $res = $modelUserTagsCat->updateUserTagsCat(intval($id), $request->except('_url'));
    return $res['code'] == 0 ? $this->toJson(self::SUCCESS) : $this->toJson(self::ERROR, [], $res['msg']);
}

/**
 * [addTagsCat 添加分类]

 */
public function delTagsCat($id)
{
    $id = intval($id);
    if ($id <= 0) {
        $this->toJson(self::ERROR, [], '参数错误');
    }
    $modelUserTagsCat = new UserTagsCat();
    $res = $modelUserTagsCat->delUserTagsCat($id);
    return $res['code'] == 0 ? $this->toJson(self::SUCCESS) : $this->toJson(self::ERROR, [], $res['msg']);
}

    public function myBag(Request $request)
    {

        $data=$request->all();

        $query = \DB::connection("api")->table('gift_bag')
            ->join('gift_library', 'gift_bag.gift_id', '=', 'gift_library.gift_id')
            ->join('user', 'gift_bag.user_id', '=', 'user.user_id')
            ->where('gift_bag.user_id', $data['user_id'])
            ->select('gift_library.name', 'gift_library.gift_id', 'gift_bag.avail', \DB::raw('sum(zb_gift_bag.avail * zb_gift_library.price) as totalPrice'))
            ->groupBy(['gift_library.gift_id'])
            ->orderBy(\DB::raw('sum(zb_gift_bag.avail * zb_gift_library.price)'));
        $pageSize = $request->input('limit', 10); // 默认每页10条记录
        $results = $query->paginate($pageSize);
        $queryAll = \DB::connection("api")->table('gift_bag')
            ->join('gift_library', 'gift_bag.gift_id', '=', 'gift_library.gift_id')
            ->join('user', 'gift_bag.user_id', '=', 'user.user_id')
            ->where('gift_bag.user_id', $data['user_id'])
            ->select(\DB::raw('sum(zb_gift_bag.avail * zb_gift_library.price) as totalPrice'));
        $all = $queryAll->first()->totalPrice;
        $results = json_decode(json_encode($results, JSON_UNESCAPED_UNICODE), true);
        $results['all'] = $all;

        return $this->toJson(self::SUCCESS, $results, "成功");
    }


}
